//
//  WXTransferModule.m
//  XYLib
//
//  Created by Richard on 2019/3/8.
//  Copyright © 2019年 XY. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "WXTransferModule.h"

@implementation WXTransferModule
WX_EXPORT_METHOD(@selector(uploadImage:completionHandler:))

#pragma mark   ------  直播间  聊天室上传图片 -------
-(void)uploadImage:(NSDictionary *)params completionHandler:(WXModuleCallback)callback
{
    NSString*urlString = [params objectForKey:@"url"];
    NSString*filePath  = [params objectForKey:@"filePath"];
    NSString*fileName  = [params objectForKey:@"fileName"];
    NSString*imageStream  = [params objectForKey:@"fileData"];
    NSData *imageData = nil;
    
    if (imageStream) {
        imageData = [[NSData alloc] initWithBase64EncodedString:imageStream options:NSDataBase64DecodingIgnoreUnknownCharacters];
    } else if (filePath) {
        UIImage*image = [UIImage imageWithContentsOfFile:filePath];
        //此处是对图片进行压缩,压缩的 比例是公司自己对于上传图片的标准要求
        if (image) {
            imageData = UIImageJPEGRepresentation(image, 0.5);
        }
    }
    
    if (!imageData || !urlString) {
        callback(@{@"result":@"error"});
        return;
    }
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
    request.HTTPMethod = @"POST";
    //分界线的标识符  WebkitfromBoundaryrtz0afzlwJUy0H4U
    NSString *TWITTERFON_FORM_BOUNDARY = @"WebkitfromBoundaryrtz0afzlwJUy0H4U";
    //分界线 --WebkitfromBoundaryrtz0afzlwJUy0H4U
    NSString *MPboundary=[[NSString alloc] initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 WebkitfromBoundaryrtz0afzlwJUy0H4U--
    NSString *endMPboundary=[[NSString alloc] initWithFormat:@"%@--",MPboundary];
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //添加分界线，换行
    [body appendFormat:@"%@\r\n",MPboundary];
    //声明file字段，文件名为currentImage.png

    if (!fileName) {
        NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
        formatter.dateFormat=@"yyyyMMddHHmmss";
        NSString *str=[formatter stringFromDate:[NSDate date]];
        fileName=[NSString stringWithFormat:@"%@.jpg",str];
    }
    [body appendFormat:@"%@", [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"jpg\"; filename=\"%@\"\r\n",fileName]];
    //声明上传文件的格式
    [body appendFormat:@"Content-Type: image/jpg\r\n\r\n"];
    //    NSLog(@"网络请求body:%@",body);
    //声明结束符：--WebkitfromBoundaryrtz0afzlwJUy0H4U--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    [myRequestData appendData:imageData];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置Content-Length
//    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:myRequestData completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //网络请求失败
        if (error != nil) {
            callback(@{@"result":@"error"});
            return;
        }
        //成功进行解析
        NSError *jsonError = nil;
        NSMutableDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
        if (jsonError || dic == nil) {
            callback(@{@"result":@"error",@"fileName:":fileName});
        }else{
            callback(@{@"result":@"success",@"url":dic[@"url"],@"fileName:":fileName});
        }
    }];
    [uploadTask resume];
    imageData = nil;
}
@end
